package com.link.base.base.product.service;

import javax.annotation.Resource;

import com.link.base.base.product.dao.mybatis.mapper.ProdViewHistoryMapper;
import com.link.base.base.product.model.ProdViewHistory;
import org.springframework.stereotype.Service;
import com.link.core.basic.dao.mapper.BasicMapper;
import com.link.core.basic.service.BasicServiceImpl;

import java.util.List;


/**
 * @author KuangRuifeng
 * created 2018-11-08
 * comments 产品浏览记录serviceImpl
 */
@Service
public class ProdViewHistoryServiceImpl extends BasicServiceImpl<ProdViewHistory> implements ProdViewHistoryService {

    @Resource
    private ProdViewHistoryMapper prodViewHistoryMapper;

    @Resource
    private ProdViewHistoryService prodViewHistoryService;

    @Override
    public BasicMapper<ProdViewHistory> getBasicMapper() {
        return prodViewHistoryMapper;
    }

    /**
     * 根据客户id和产品id添加或更新浏览记录
     * @author KuangRuifeng
     * @date 2018年11月9日
     * @param prodViewHistory
     * @return 新记录
     * @throws Exception
     */
    @Override
    public ProdViewHistory upsertViewHis(ProdViewHistory prodViewHistory) throws Exception {
        // 先根据客户id和产品id查询是否有记录，有则更新没有就新建
        List<ProdViewHistory> prodViewHistories =  prodViewHistoryService.queryByExamplePage(prodViewHistory);
        // 一个客户id和一个产品id只能查出一条记录
        if (prodViewHistories != null && prodViewHistories.size() > 0) {
            ProdViewHistory pvh = prodViewHistories.get(0);
            pvh.setCumulateView(pvh.getCumulateView() + 1);
            pvh.setStartTime(prodViewHistory.getStartTime());
            pvh.setEndTime(prodViewHistory.getEndTime());
            prodViewHistoryService.update(pvh);
            return prodViewHistoryService.queryById(pvh);
        } else {
            // 新建时浏览次数为一次
            prodViewHistory.setCumulateView(1);
            prodViewHistoryService.insert(prodViewHistory);
            return prodViewHistoryService.queryById(prodViewHistory);
        }
    }
}

